package com.kevin.learn.leetcode;

import com.alibaba.fastjson.JSON;
import com.kevin.learn.domain.TreeNode;

public class 二叉树 {

    public static void main(String[] args) {
        TreeNode treeNode = initData();

        int count = count(treeNode);
        System.out.println("树节点总数: " + count);

//        invertTree(treeNode);
        
        System.out.println(JSON.toJSON(treeNode));
    }

    /**
     * 计算树节点总数
     *
     * @param root
     * @return
     */
    private static int count(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + count(root.getLeft()) + count(root.getRight());
    }

    /**
     * 将整棵树的节点翻转
     *
     * @param root
     * @return
     */
    private static TreeNode invertTree(TreeNode root) {
        if (root == null)
            return null;

        /**** 前序遍历位置 ****/
        // root 节点需要交换它的左右子节点
        TreeNode temp = root.getLeft();
        root.setLeft(root.getRight());
        root.setRight(temp);

        // 让左右子节点继续翻转它们的子节点
        invertTree(root.getLeft());
        invertTree(root.getRight());
        return root;
    }


    private static TreeNode initData() {
        TreeNode treeNode = new TreeNode(1);

        // 左
        TreeNode left2 = new TreeNode(2);
        TreeNode left4 = new TreeNode(4);


        left2.setLeft(left4);
        treeNode.setLeft(left2);

        // 右
        TreeNode right3 = new TreeNode(3);
        treeNode.setRight(right3);

        return treeNode;
    }
}
